import 'package:dio/dio.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/ui/controller/MyPageState.dart';
import 'package:flutter_juwo/ui/model/base_entity.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';

import 'model/user_type_entity.dart';

class UserTagsPage extends StatefulWidget {
  String arr = "";
  String platId = "";
  String id = "";

  UserTagsPage(this.arr, this.platId, this.id);

  @override
  _UserTagsPageState createState() => _UserTagsPageState();
}

class _UserTagsPageState extends State<UserTagsPage> {
  MyPageState ps = MyPageState.LOADING;
  UserTypeEntity entity;
  List<String> ids = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: UiUtils.appBar(context, "用户标签"),
      body: getBody(),
    );
  }

  getBody() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      return Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: ListView(
              children: <Widget>[
                UiUtils.divider(height: 2),

                ///顶部文字说明
                getRow1(),

                ///标签内容
                getRow2(),

                getRow4(),

                getRow5()
              ],
            ),
          )
        ],
      );
    }
  }

  void getData() {
    FormData formData = FormData.from({"id": widget.id});
    DioManager.getInstance().get(Api.USER_USERTAGS, formData, (json) {
      entity = UserTypeEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }
      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        NavigatorUtils.goBack(context);
        return;
      }
      for (int i = 0; i < entity.data.tagList.length; i++) {
        if (entity.data.tagList[i].status == 1) {
          ids.add(entity.data.tagList[i].id);
        }
      }
      ps = MyPageState.HAVE_DATA;
      setState(() {});

      print("json--------$json");
    }, (err) {
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
      NavigatorUtils.goBack(context);
    });
  }

  getRow1() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30), 0, ScreenUtil().setWidth(30)),
      child: Text(
        "您最近购买过/感兴趣的商品分类：",
        style:
            TextStyles.custom(30, Colours.appC2, Font.PingFangMedium),
      ),
    );
  }

  getRow2() {
    return GridView.count(
      shrinkWrap: true,
      //水平子Widget之间间距
      crossAxisSpacing: ScreenUtil().setWidth(20),
      //垂直子Widget之间间距
      mainAxisSpacing: ScreenUtil().setWidth(20),
      //GridView内边距
      padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
      //一行的Widget数量
      crossAxisCount: 3,
      //子Widget宽高比例
      childAspectRatio: 2.6,
      //子Widget列表
      children: getWidgetList(),
    );
  }

  getWidgetList() {
    List<Widget> list = [];
    for (int i = 0; i < entity.data.tagList.length; i++) {
      list.add(getItem(entity.data.tagList[i]));
    }
    return list;
  }

  Widget getItem(UserTypeDataTaglist tag) {
    return GestureDetector(
      onTap: () {
        if (ids.contains(tag.id)) {
          ids.remove(tag.id);
        } else {
          if (ids.length == 6) {
            ToastUtil.showShortErrToast("最多选择6个");
            return;
          }
          ids.add(tag.id);
        }
        setState(() {});
      },
      child: Container(
        alignment: Alignment.center,
        decoration: getBoxDecoration(tag.id),
        child: Text(
          tag.tagName,
          style: TextStyles.custom(
              32, Colours.appC2, Font.PingFangMedium),
        ),
      ),
    );
  }

  getBoxDecoration(String id) {
    return BoxDecoration(
        border: Border.all(
            color: ids.contains(id) ? Colours.appC16 : Colors.grey,
            width: ScreenUtil().setWidth(2)),
        borderRadius: BorderRadius.circular(6));
  }

  getRow4() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(60),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30)),
      child: UiUtils.bottomBotton("提交审核", () {
        putData();
      }),
    );
  }

  getRow5() {
    return GestureDetector(
      onTap: () {
        NavigatorUtils.goBack(context);
      },
      child: Container(
          alignment: Alignment.center,
          padding: EdgeInsets.fromLTRB(
              ScreenUtil().setWidth(30),
              ScreenUtil().setWidth(0),
              ScreenUtil().setWidth(30),
              ScreenUtil().setWidth(30)),
          child: Text(
            "返回上一步",
            style: TextStyles.custom(
                28, Colours.appC16, Font.PingFangMedium),
          )),
    );
  }

  void putData() {
    if (ids.length < 3) {
      ToastUtil.showShortErrToast("选择至少3个感兴趣的分类");
      return;
    }

    UiUtils.showMyDialog(context, text: "正在提交");

    String usertags = getTags();
    FormData formData = FormData.from({
      "id": widget.id,
      "platId": widget.platId,
      "arr": widget.arr,
      "usertags": usertags
    });
    DioManager.getInstance().post(Api.USER_SAVEPLATACCOUNT, formData, (json) {
      print("json$json");
      BaseEntity entity = BaseEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }
      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        return;
      }
      NavigatorUtils.goBack(context);
      ToastUtil.showShortToast("提交成功！");

      NavigatorUtils.goBackWithParams(context, true);
      NavigatorUtils.goBackWithParams(context, true);
    }, (err) {
      NavigatorUtils.goBack(context);
      ToastUtil.showShortErrToast(err);
      return;
    });
  }

  String getTags() {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i <= ids.length - 1; i++) {
      sb.write(ids[i]);

      if (i != ids.length - 1) {
        sb.write(",");
      }
    }

    return sb.toString();
  }
}
